/*
 * *
 * author:cgm
 * date:18-5-16 下午4:34
 * /
 */

package com.kaili.common.checkField;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * package name:com.kaili.common.checkField
 * author:hasee
 * date :2018/5/16
 * project:micro-service
 */
public class IdCardFeildCheck implements CheckFieldHandler {
    private static final String IdCardRegExp = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";

    @Override
    public boolean checkField(Object obj) {
        String idCard = ((String) obj).toUpperCase();
        Pattern pattern = Pattern.compile(IdCardRegExp);
        Matcher matcher = pattern.matcher(idCard);
        if (!matcher.matches()) {
            return false;
        }
        int[] w = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; // 加权因子
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum = sum + Integer.parseInt(idCard.substring(i, i + 1)) * w[i];
        }
        String[] v = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"}; // 校验码
        int y = sum % 11;
        if (!v[y].equals(idCard.substring(17))) {// 第18位校验码错误
            return false;
        }
        return true;
    }
}
